import { ref, computed } from 'vue'
import { defineStore } from 'pinia'

export interface User {
  id: number
  username: string
  name: string
  email: string
  avatar?: string
  roles: string[]
}

export const useUserStore = defineStore('user', () => {
  const token = ref<string | null>(localStorage.getItem('token'))
  const userInfo = ref<User | null>(null)
  const permissions = ref<string[]>([])

  const isAuthenticated = computed(() => !!token.value)
  const hasRole = (role: string) => userInfo.value?.roles.includes(role) ?? false
  const hasPermission = (permission: string) => permissions.value.includes(permission)

  // 登录
  const login = async (username: string, password: string) => {
    try {
      // 模拟登录 API 调用
      const response = await mockLogin(username, password)

      token.value = response.token
      userInfo.value = response.user
      permissions.value = response.permissions

      localStorage.setItem('token', response.token)
      localStorage.setItem('userInfo', JSON.stringify(response.user))

      return { success: true }
    } catch (error) {
      return { success: false, message: error instanceof Error ? error.message : '登录失败' }
    }
  }

  // 退出登录
  const logout = () => {
    token.value = null
    userInfo.value = null
    permissions.value = []

    localStorage.removeItem('token')
    localStorage.removeItem('userInfo')
  }

  // 获取用户信息
  const getUserInfo = async () => {
    try {
      // 模拟获取用户信息 API
      const response = await mockGetUserInfo()
      userInfo.value = response.user
      permissions.value = response.permissions
      return response
    } catch (error) {
      console.error('获取用户信息失败:', error)
      logout()
    }
  }

  // 初始化用户信息
  const initUserInfo = () => {
    const savedUserInfo = localStorage.getItem('userInfo')
    if (savedUserInfo && token.value) {
      try {
        userInfo.value = JSON.parse(savedUserInfo)
        getUserInfo() // 刷新用户信息
      } catch (error) {
        console.error('解析用户信息失败:', error)
        logout()
      }
    }
  }

  return {
    token,
    userInfo,
    permissions,
    isAuthenticated,
    hasRole,
    hasPermission,
    login,
    logout,
    getUserInfo,
    initUserInfo
  }
})

// 模拟登录 API
const mockLogin = (username: string, password: string): Promise<{
  token: string
  user: User
  permissions: string[]
}> => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (username === 'admin' && password === '123456') {
        resolve({
          token: 'mock-jwt-token-' + Date.now(),
          user: {
            id: 1,
            username: 'admin',
            name: '管理员',
            email: 'admin@example.com',
            avatar: '',
            roles: ['admin', 'user']
          },
          permissions: ['user:read', 'user:write', 'product:read', 'product:write', 'order:read', 'order:write']
        })
      } else {
        reject(new Error('用户名或密码错误'))
      }
    }, 1000)
  })
}

// 模拟获取用户信息 API
const mockGetUserInfo = (): Promise<{
  user: User
  permissions: string[]
}> => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        user: {
          id: 1,
          username: 'admin',
          name: '管理员',
          email: 'admin@example.com',
          avatar: '',
          roles: ['admin', 'user']
        },
        permissions: ['user:read', 'user:write', 'product:read', 'product:write', 'order:read', 'order:write']
      })
    }, 500)
  })
}
